<?php

class UserController extends UserBaseC {
    public $layout = 'theme.views.layouts.frontNoContent';
    /**
     * Declares class-based actions.
     * 登录,,注册,,验证,,找回密码,,等等,,控制器
     */
    public function actions() {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
                'minLength' => 4,
                'maxLength' => 4,
                'transparent' => true,
            ),
        );
    }

    //登录
    public function actionLogin(){
        if(yii::app()->user->isLogin()){
            $this->redirect(array("/user/member/index"));    
        }
        $this->layout = 'theme.views.layouts.frontNoContent';
        if(IS_POST){
            if(!$this->createAction('captcha')->validate($_POST['verifyCode'], false)){
                $this->error('验证码不正确');
            }
            if(empty($_POST['UserName']) || empty($_POST['Password'])){
                $this->error('用户名或密码不能为空');
            }

            if(yii::app()->user->login($_POST['UserName'], $_POST['Password'])){
                $this->success('成功登录',"/user/member/index");
                //$this->redirect(array("/user/member/index"));    
            }else{
                $this->error(yii::app()->user->getError());
            }                   
       
        }
        $this->render();
    }


    // $this->widget('CCaptcha',array('showRefreshButton'=>true,'clickableImage'=>true,'buttonLabel'=>'看不清'));
    //买家注册
    public function actionBuyersRegister(){
        if(yii::app()->user->isLogin()){
            $this->redirect(array("/user/member/index"));    
        }        
        $this->layout = 'theme.views.layouts.frontNoContent';
        $model = MemberModel::model();
        $model->setScenario('front_buyers');          
        $model->setIsNewRecord(true);
        //$model = new MemberModel('front_buyers');        
        if(IS_POST){
            $model->attributes = $_POST;
            $model->Type = 0;
            //用户名是手机号或者是邮箱
            if($_POST['rigisterType'] == 1){
                $model->Email = '';
            }else{
                $model->Phone = '';
            }

            if($model->Password != $_POST['Repassword']){
                $this->error('两次密码不一致');
            }

            //邮箱填的验证码
            if(!empty($model->Email) && !$valid = $this->createAction('captcha')->validate($_POST['verifyCode'], false)){
                $this->error('验证码不正确');
            }
          
            if($model->validate()){
                if(!empty($this->Phone)){
                    if(!SnsVerification::getInstance()->verification($_POST['phone_captcha'],$this->Phone)){
                        $this->error(SnsVerification::getInstance()->getError());
                        return false;
                    }
                }
                $model->save(false);                
                //注册成功,,还需要进行验证则跳到验证那，如果不需要进行验证则直接跳到用户中心
                if($model->Status == 0){
                    //如果状态为0则需要验证
                    $this->success('提交成功',$this->createUrl('regEmailSuccesed', array('mail' => $model->Email)));
                }else{
                    //登录并且是跳到会员中心主页
                    yii::app()->user->login($model->UserName, $_POST['Repassword']);
                $this->success('注册成功',$this->createUrl("/user/member/index"));
                }               
            }else{
                $this->error($model->getOneError());
            }
        }
        $this->render();
    }

    /**
     * 买家注册后邮箱验证
     * @return [type] [description]
     */
    public function actionRegEmailSuccesed($mail) {
        if(yii::app()->user->isLogin()){
            $this->redirect(array("/user/member/index"));    
        }        
        set_time_limit(0);
        if((($model = MemberModel::model()->find(BaseModel::getC(array('Email' => $mail)))) && $model->Status == 1)){
            if($model){
                $this->success('已经验证通过,请直接登录', $this->createUrl('login'));
            }else{
                $this->error('找不到用户记录', $this->createUrl('/front/index/index'));
            }
        }
        if($model = MemberVerificationModel::getOneData($mail)){
            if($model->Status == 0){
                $time = 120 - TIME_TIME + $model->AddTime;
                if($time > 0){  
                    if(IS_AJAX){
                        $this->error("刚发送邮件，离下次再发邮件还有{$time}秒");                      
                    }else{
                        $content = "刚发送邮件，离下次再发邮件还有{$time}秒";
                        $this->assign('content', $content);
                        $this->assign('mail', $mail);
                        $this->render();
                        exit;                          
                    }                 
                }             
            }
        }
        //发送一邮件
        if(MemberModel::sendEmail($mail)){
            $content = "邮件发送成功";
            $status = 1;   
        }else{
            $content = yii::app()->user->getFlash(); 
            $status = 0;      
        }
        if(IS_AJAX){
            $this->ajaxReturn(array('info' => $content, 'status' => $status));
        }
        $this->assign('content', $content);
        $this->assign('mail', $mail);
        $this->render();  
    }

    public function actionVerify($confirmation_token = ''){
        $return  = MemberVerificationModel::verification($confirmation_token);
        if($return == 1){
            $this->success('验证成功',$this->createUrl('login'));
        }else if($return == 0){
            $this->error('找不到记录',$this->createUrl('buyersRegister'));
        }else{
            $this->error('key已经过期,将重新发送',$this->createUrl('regEmailSuccesed', array('mail' => yii::app()->user->getFlash())));
        }
    }

    //商家注册
    public function actionSellerRegister(){
        $model = MemberModel::model();
        $model->setScenario('front_seller');          
        $model->setIsNewRecord(true);        
        //$model = new MemberModel('front_seller');
        if(IS_POST){
            $model->attributes = $_POST;
            $model->Type = 1;
            if($model->Password != $_POST['Repassword']){
                $this->error('两次密码不一致');
            }
            if($model->validate()){
                if(!SnsVerification::getInstance()->verification($_POST['phone_captcha'],$this->Phone)){
                    $this->error(SnsVerification::getInstance()->getError());
                    return false;
                }
                $model->save(false);                                 
                //登录并且是跳到会员中心主页
                yii::app()->user->login($model->UserName, $_POST['Repassword']);
                $this->success('注册成功',$this->createUrl('/user/member/index'));
            }else{
               $this->error($model->getOneError()); 
            }
        }   
        $this->render();
    }

    

    public function actionLogout() {
        Yii::app()->user->logout();
        $this->redirect($this->createUrl('/front/index/index'));
    }

    //发送短信验证码
    public function actionSendcode() {
        $moblie = Yii::app()->request->getParam('moblie');
        if (empty($moblie)) {
            $this->error('手机号不能为空！');
        }
        $key = md5(Tool::getForwardedForIp());
        if (Yii::app()->cache->get($key)) {
            $this->error('请60秒后再次发送！');
        }
        if (defined('YII_DEBUG') && YII_DEBUG == false) {
            $rKey = md5($moblie);
            $redisKey = (int) RedisCluster::getInstance()->get($rKey);
            if ($redisKey >= 5) {
                $this->error('该手机号今日已达最大发送数！');
            }
        }
        if (SnsVerification::getInstance()->send($moblie)) {
            if (defined('YII_DEBUG') && YII_DEBUG == false) {
                $redisKey = (int) $redisKey + 1;
                $time = strtotime(date('Y-m-d 23:59:59')) - time();
                RedisCluster::getInstance()->set($rKey, $redisKey, $time);
            }
            Yii::app()->cache->set($key, 1, 60);
            $this->success('短信验证码已经发送！');
        } else {
            $this->error('验证码发送失败！');
        }
    }

    /**
     * 找回密码
     * @return [type] [description]
     */
    public function actionFindPassword(){
        if(IS_POST){

        }
        $this->render();
    }



    /**
     * 用户注册,,模仿锤子手机来
     * //前台注册
     * @return [type] [description]
     */
    public function actionLoginRegister(){
        $this->layout = false;
        $otype = Yii::app()->request->getParam('otype');//操作类型
        if($otype == 0){//这是注册
            $model = new RegisterForm();          
            if(isset($_POST['RegisterForm'])){            
                $model->attributes = $_POST['RegisterForm'];  
                //然后再验证手机短信是否是需要验证，，，因为手机短信当如果正确的话是直接被踢除了，所以需要其它的验证通过了之后再验证手机验证码是否正确，这样
                //就不会存在其它验证不通过，手机验证码验证通过让验证码失效                      
                if($model->validate() && $model->checkPhoneCode()){
                    $model->register();
                    $this->success('成功注册');//如果是邮箱则状态还是0，如果是手机则可直接登录了
                }
            }
            $this->render('',array('model' => $model));            
        }else{//这是登录
            $model = new LoginForm();          
            if(isset($_POST['LoginForm'])){
                 $model->attributes =  $_POST['LoginForm'];
                 if($model->validate()){
                    $this->success('登录成功');
                 }    
            }
            $this->render('',array('model' => $model));      
        }
    }    
         

}
